package conf

import (
	"github.com/mitchellh/mapstructure"
	"github.com/spf13/viper"
)

type ProjectConfig struct {
	AppName string `yaml:"appName"`
	AppId   int    `yaml:"appId"`
	Env     string `yaml:"env"`
	Port    string `yaml:"port"`
	UrlPath string `yaml:"urlPath"`
}

var Config = ProjectConfig{}

func LoadConfig() error {
	viper.AutomaticEnv()
	env := viper.GetString("ENV")

	configName := ""
	if env == "" || env == "prod" {
		configName = "config"
	} else {
		configName = "config_" + env + ""
	}
	viper.SetConfigName(configName)
	viper.AddConfigPath(".")
	viper.AddConfigPath("configs")
	viper.AddConfigPath("../configs/")

	err := viper.ReadInConfig()
	if err != nil {
		return err
	}

	err = viper.Unmarshal(&Config, DecoderConfigTagYaml)
	if err != nil {
		return err
	}
	Config.Env = env

	return nil
}

// yaml标签的配置解码
func DecoderConfigTagYaml(config *mapstructure.DecoderConfig) {
	config.TagName = "yaml"
}
